package yyds.sniarbtej.transformer.intellij;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import yyds.sniarbtej.transformer.BaseClassTransformer;
import yyds.sniarbtej.transformer.ClassRewriter;

public final class CreateLicenses extends BaseClassTransformer {
    public String canTransformClassName() {
        return "com/intellij/openapi/application/PathManager";
    }

    public byte[] rewrite(byte[] in) {
        return transform(in, new ClassRewriter() {
            @Override
            public void rewriteMethod(MethodNode node) {
                if ("getConfigPath".equals(node.name) && "()Ljava/lang/String;".equals(node.desc)) {
                    InsnList insn = node.instructions;
                    AbstractInsnNode retIns = null;

                    for (AbstractInsnNode abstractInsnNode : insn) {
                        if (abstractInsnNode.getOpcode() == Opcodes.ARETURN) {
                            retIns = abstractInsnNode;
                        }
                    }

                    if (retIns != null) {
                        insn.insertBefore(retIns, new VarInsnNode(Opcodes.ASTORE, 0));
                        insn.insertBefore(retIns, new VarInsnNode(Opcodes.ALOAD, 0));
                        /* createFakeLicenses */
                        insn.insertBefore(retIns, new MethodInsnNode(Opcodes.INVOKESTATIC, methodOverride, "C2", "(Ljava/lang/Object;)V", false));
                        insn.insertBefore(retIns, new VarInsnNode(Opcodes.ALOAD, 0));
                    }
                }
            }
        });
    }
}
